package cn.my.framework.config.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * Created by zhangl_lc on 2017/7/7.
 */
@Component("myAccessDecisionManager")
public class MyAccessDecisionManager implements AccessDecisionManager {

    Logger logger = LoggerFactory.getLogger(MyAccessDecisionManager.class);

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        if (configAttributes == null) {
            return;
        }

        FilterInvocation filterInvocation = (FilterInvocation) object;
        logger.debug(">>>> the visit url is : {}",filterInvocation.getRequestUrl());

        Collection<GrantedAuthority> userHasRoles =
                (Collection<GrantedAuthority>) authentication.getAuthorities();
        for(GrantedAuthority ga : userHasRoles){
            if(ga.getAuthority().toLowerCase().contains("role_anon")){
                throw new AccessDeniedException("无访问权限");
            }
        }

        for(ConfigAttribute ca : configAttributes ){
            Iterator<GrantedAuthority> iter = userHasRoles.iterator();
            while (iter.hasNext()){
                if(iter.next().getAuthority().equals(ca.getAttribute())){
                    return;
                }
            }
        }

        throw new AccessDeniedException("无访问权限");
    }
    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
